<?php
// +----------------------------
// | Created by PhpStorm
// +----------------------------
// | Author: YnnSon
// +----------------------------
namespace app\api\service;

use app\lib\exception\UploadException;
use think\Config;
use think\Request;
use Yurun\Util\HttpRequest;
use Yurun\Util\YurunHttp\Stream\FileStream;

class Ocr
{
    /**
     * @Desc 行驶证OCR
     *
     * @param $param
     *
     * @return array
     */
    public static function drivingOcr($param)
    {
        $url = Config::get('wechat.driving_ocr_url');
        $appcode = Config::get('wechat.driving_ocr_appcode');
        $license_image = str_replace('\\', '/', $param['image']);
        $image = Request::instance()->server('document_root') . DS . 'upload' . DS . 'api' . DS . 'image' . DS . $license_image;
        $file = new FileStream($image);
        $binary = $file->read(filesize($image));
        $file->close();
        $http = new HttpRequest();
        $header = [
            'Authorization' => "APPCODE {$appcode}",
            'Content-Type'  => 'application/json; charset=UTF-8',
        ];
        $requestBody = [
            'image'     => base64_encode($binary),
            'configure' => "{'side':'face'}",
        ];
        $requestBody = json_encode($requestBody);
        $response = $http->headers($header)->post($url, $requestBody, 'json');
        if (200 != $response->httpCode()) {
            throw new UploadException([
                'code'      => 400,
                'message'   => '图片识别失败',
                'errorCode' => 50002,
            ]);
        }
        $result = $response->json(true);
        $vin = strlen($result['vin']) >= 6 ? substr($result['vin'], -6) : '';
        return [
            'license_number'         => $result['plate_num'],
            'license_typename'       => $result['vehicle_type'],
            'user_name'              => $result['owner'],
            'user_address'           => $result['addr'],
            'license_nature'         => $result['use_character'],
            'vehicle_brand'          => $result['model'],
            'vehicle_identification' => $result['vin'],
            'vin'                    => $vin,
            'engine_identification'  => $result['engine_num'],
            'license_register_date'  => $result['register_date'],
            'license_grant_date'     => $result['issue_date'],
            'license_image'          => $license_image,
        ];
    }
}